<?php


namespace helper\calc;


class Context
{
  protected $fnt = array(), $cst = array( 'PI' => M_PI, 'π' => M_PI );

  public function fn($name, array $args)
  {
    if (!isset($this->fnt[$name]))
      throw new \Exception('运行时错误：未定义函数:' . $name);

    return (float) call_user_func_array($this->fnt[$name], $args);
  }

  public function cs($name)
  {
    if (!isset($this->cst[$name]))
      throw new \Exception('运行时错误：未定义的常量:' . $name);

    return $this->cst[$name];
  }

  public function def($name, $value = null)
  {
    // einfacher wrapper
    if ($value === null) $value = $name;

    if (is_callable($value))
      $this->fnt[$name] = $value;

    elseif (is_numeric($value))
      $this->cst[$name] = (float) $value;

    else
      throw new \Exception('参数数量不对应');
  }
}